#!/usr/bin/env bash

# TODO:
# * include a function to delete older directories by days or mins
# * include a function to delete newest directories by days or mins

help(){
    cat<<__EOF__
    usage: m dir [ tree | size | delete | help ]

    Examples:
      m dir tree        # tree view of folders in the current path
      m dir tree /path  # tree view of folders in a specific path

      m dir delete empty          # delete empty folders recursively in the current path
      m dir delete empty /path    # delete empty folders recursively in a specific path

      m dir delete dsfiles        # delete .DS_Store files recursively in the current path
      m dir delete dsfiles /path  # delete .DS_Store files recursively in a specific path

      m dir size        # calculate current folder size
      m dir size /path  # calculate folder size in a specific path

__EOF__

}

confirm () {
		# call with a prompt string or use a default
		read -r -p "${1:-Are you sure? [y/n]} " response
		case $response in
			[yY][eE][sS]|[yY])
				true
				;;
			*)
				false
				;;
    esac
}

tree_dirs(){
    dir="${1:-.}"
    ls -R "${dir}"| grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
}


delete_empty(){
    DIRS="${@:-.}"
    echo "Folders to be deleted: "
    find "${DIRS}" -type d -empty -print
    confirm && find "${DIRS}" -type d -empty -delete
}


delete_dsfiles(){
    DIRS="${@:-.}"
    echo "Files to be deleted: "
    find "${DIRS}" -type f -name .DS_Store -print
    confirm && find "${DIRS}" -type f -name .DS_Store -print -delete
}


folder_size(){
    dir="${@:-.}"
    echo "Folder size:"
    du -sh "${dir}"
}


delete(){
    case "$1" in
        empty)
            shift;
            delete_empty "$@"
            ;;
        dsfiles)
            shift;
            delete_dsfiles "$@"
            ;;
        *)
            help && exit 1
            ;;
    esac
}



case "$1" in
    help)
        help
        ;;
    tree)
        shift
        tree_dirs "$@"
        ;;
    delete)
        shift;
        delete "$@"
        ;;
    size)
        shift
        folder_size "$@"
        ;;
    *)
        help
        ;;
esac

# vim: ts=4 sw=4 softtabstop=4 expandtab
